package com.miaostars.level.listener;

import com.miaostars.level.manager.PlayerDataManager;
import com.miaostars.level.data.Rank;
import com.miaostars.level.utils.CPSValidator;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;

public class JoinListener implements Listener {
    private final PlayerDataManager dataManager;

    public JoinListener(PlayerDataManager dataManager) {
        this.dataManager = dataManager;
    }

    @EventHandler
    public void onPlayerJoin(PlayerJoinEvent event) {
        Player player = event.getPlayer();
        UUID uuid = player.getUniqueId();

        // 1. 初始化玩家数据（从数据库加载）
        dataManager.loadPlayerData(uuid);
        
        // 2. 获取玩家等级并更新显示名
        updatePlayerPrefix(player);
        
        // 3. 重置CPS检测记录
        CPSValidator.resetPlayerClicks(uuid);
        
        // 4. 发送欢迎消息（可选）
        player.sendMessage("§a欢迎回到服务器！您的等级已同步更新");
    }

    private void updatePlayerPrefix(Player player) {
        // 获取玩家数据
        PlayerStats stats = dataManager.getStats(player.getUniqueId());
        
        // 计算等级
        Rank rank = Rank.fromStats(stats);
        
        // 更新玩家显示名和Tab列表
        player.setDisplayName(rank.getPrefix() + player.getName());
        player.setPlayerListName(rank.getPrefix() + player.getName());
        
        // 使用NametagEdit API（需额外集成）
        // NametagAPI.setPrefix(player, rank.getPrefix());
    }
}